package com.example.android01;

import android.util.Log;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * MQTT客户端封装类，提供MQTT连接、消息接收和发布功能
 * 外部类可通过实现MessageListener接口监听MQTT消息
 */
public class MqttPublisher {
    private static final String TAG = "MqttClientWrapper";
    private MqttClient mqttClient;
    private final String brokerUrl;
    private final String clientId;
    private final int qos;
    private final String username;
    private final String password;
    private MessageListener messageListener;
    private ConnectionListener connectionListener;
    private boolean isConnected = false;

    // 消息监听器接口，供外部实现
    public interface MessageListener {
        void onMessageReceived(String topic, String message);
    }

    // 连接状态监听器接口
    public interface ConnectionListener {
        void onConnected();
        void onConnectionLost(Throwable cause);
    }

    /**
     * 构造函数
     * @param brokerUrl MQTT代理服务器地址
     * @param clientId 客户端ID
     * @param qos 消息质量等级
     * @param username MQTT用户名
     * @param password MQTT密码
     */
    public MqttPublisher(String brokerUrl, String clientId, int qos, String username, String password) {
        this.brokerUrl = brokerUrl;
        this.clientId = clientId;
        this.qos = qos;
        this.username = username;
        this.password = password;
    }

    /**
     * 设置消息监听器
     * @param listener 消息监听器
     */
    public void setMessageHandler(MessageListener listener) {
        this.messageListener = listener;
    }

    /**
     * 设置连接状态监听器
     * @param listener 连接状态监听器
     */
    public void setConnectionListener(ConnectionListener listener) {
        this.connectionListener = listener;
    }

    /**
     * 连接到MQTT代理服务器
     */
    public void connect() {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                Log.d(TAG, "Already connected to MQTT broker");
                return;
            }

            mqttClient = new MqttClient(brokerUrl, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setKeepAliveInterval(60);

            // 设置用户名和密码
            if (username != null && !username.isEmpty()) {
                options.setUserName(username);
            }
            if (password != null && !password.isEmpty()) {
                options.setPassword(password.toCharArray());
            }

            mqttClient.setCallback(new MqttCallbackExtended() {
                @Override
                public void connectComplete(boolean reconnect, String serverURI) {
                    Log.d(TAG, "Connection complete: " + serverURI + ", Reconnect: " + reconnect);
                    isConnected = true;
                    if (connectionListener != null) {
                        connectionListener.onConnected();
                    }
                }

                @Override
                public void connectionLost(Throwable cause) {
                    Log.e(TAG, "Connection lost: " + cause.getMessage());
                    isConnected = false;
                    if (connectionListener != null) {
                        connectionListener.onConnectionLost(cause);
                    }
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    String payload = new String(message.getPayload());
                    Log.d(TAG, "Message received on topic [" + topic + "]: " + payload);
                    if (messageListener != null) {
                        messageListener.onMessageReceived(topic, payload);
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    Log.d(TAG, "Message delivery complete");
                }
            });

            mqttClient.connect(options);
            Log.d(TAG, "Connected to MQTT broker: " + brokerUrl);
        } catch (MqttException e) {
            Log.e(TAG, "Failed to connect to MQTT broker", e);
            isConnected = false;
        }
    }

    /**
     * 断开MQTT连接
     */
    public void disconnect() {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.disconnect();
                Log.d(TAG, "Disconnected from MQTT broker");
            }
        } catch (MqttException e) {
            Log.e(TAG, "Failed to disconnect from MQTT broker", e);
        } finally {
            isConnected = false;
        }
    }

    /**
     * 订阅MQTT主题
     * @param topic 要订阅的主题
     */
    public void subscribe(String topic) {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.subscribe(topic, qos);
                Log.d(TAG, "Subscribed to topic: " + topic);
            } else {
                Log.e(TAG, "Cannot subscribe: Not connected to MQTT broker");
            }
        } catch (MqttException e) {
            Log.e(TAG, "Failed to subscribe to topic: " + topic, e);
        }
    }

    /**
     * 发布MQTT消息
     * @param topic 目标主题
     * @param message 消息内容
     */
    public void publish(String topic, String message) {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                MqttMessage mqttMessage = new MqttMessage(message.getBytes());
                mqttMessage.setQos(qos);
                mqttClient.publish(topic, mqttMessage);
                Log.d(TAG, "Published message to topic [" + topic + "]: " + message);
            } else {
                Log.e(TAG, "Cannot publish: Not connected to MQTT broker");
            }
        } catch (MqttException e) {
            Log.e(TAG, "Failed to publish message to topic: " + topic, e);
        }
    }

    /**
     * 检查MQTT连接状态
     * @return 是否已连接
     */
    public boolean isConnected() {
        return mqttClient != null && mqttClient.isConnected();
    }
}